<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<title>订单列表</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="keywords" content="" />
	<meta http-equiv="Pragma" content="no-cache">
	<meta http-equiv="Cache-Control" content="no-cache, must-revalidate">

	<!-- Custom Theme files -->
<link href="../css/app/bootstrap.css" type="text/css" rel="stylesheet" media="all">
<link href="../css/app/style.css" type="text/css" rel="stylesheet" media="all">

	<link href="../css/orderlist.css" type="text/css" rel="stylesheet" media="all">
	<!-- //Custom Theme files -->
<!-- js -->
<script src="../js/jquery-2.2.3.min.js"></script>  
<script src="../js/bootstrap.js"></script>
	<script src="../js/axios.js" ></script>
<script src="../js/vue.js"></script>
<!-- //js -->

</head>
<body>
<div id="app"><!-- banner -->
	<div class="banner about-w3bnr">
		<!-- header -->
		<div class="header">
			<!-- //header-one -->
			<!-- navigation -->
			<div class="navigation agiletop-nav">
				<div class="container">
					<nav class="navbar navbar-default">
						<!-- Brand and toggle get grouped for better mobile display -->
						<div class="navbar-header w3l_logo">

							<h1><a href="index.html">重生之我要做点菜系统</a></h1>
						</div>
						<div class="collapse navbar-collapse" id="bs-megadropdown-tabs">
							<ul class="nav navbar-nav navbar-right">
								<li><a href="index.html" class="active">主页</a></li>
								<!-- Mega Menu -->
								<li>
									<a href="menu.html" class="dropdown-toggle">菜单 </a>
								</li>
								<li class="w3pages">
									<a href="orderList.html" class="dropdown-toggle">我的订单</a>
								</li>

								<li class="head-dpdn">
									<a href="login.html">登录</a>
								</li>
								<li class="head-dpdn">
									<a href="register.html">免费注册</a>
								</li>
								<li class="head-dpdn">
									<a href="http://60.205.91.68:8080/admin/admin/pages/member/chat/userchat.html" target="_blank">客服</a>
								</li>
								<li class="head-dpdn">
									<a href="../html/login.html">退出</a>
								</li>
							</ul>
						</div>
					</nav>
				</div>
			</div>
			<!-- //navigation -->
		</div>
		<!-- //header-end -->
	</div>
	<!-- //banner -->
	<!-- breadcrumb -->
	<div class="container">
		<ol class="breadcrumb w3l-crumbs">
			<li><a href="../html/index.html"><i class="fa fa-home"></i> 主页</a></li>
			<li class="active">我的订单</li>
		</ol>
	</div>
	<!-- //breadcrumb -->
	<!-- products -->
	<div class="products">
		<div class="container">

			<!-- 订单列表 -->
			<div class="order-list">
				<div v-for="(list, index) in order" :key="index" class="order-entry">
					<div class="order-header">
						<div class="order-info">
							<span class="table-id">{{ list.table_id }}号餐桌</span>
							<span class="order-code">订单编号：{{ list.order_code }}</span>
							<span class="order-date">下单时间：{{ showDate(list.order_date) }}</span>
						</div>
						<div class="order-status">
							<span class="total-price">￥{{ list.total_price }}</span>
							<div class="button-group">
								<button v-if="list.order_status === 0" @click="payfor(list)" class="pay-button">请付款</button>
								<span v-else class="paid-status">已付款</span>
								<button @click="addReview(list.id)" class="add-review-button">添加评价</button>
							</div>
						</div>
					</div>
					<ul class="order-details">
						<li v-for="(detail, index) in displayedDetails(list.id)" :key="index" class="order-item">
							<img :src="getfoodimg(detail.foodid)" alt="" class="food-img">
							<span class="food-name">{{ getFoodName(detail.foodid) }}</span>
							<span class="food-quantity">{{ detail.buynum }}份</span>
							<span class="food-price">
								￥{{getFoodDiscount(detail.foodid)}}
								<s>￥{{ getFoodPrice(detail.foodid) }}</s>
							</span>
						</li>
					</ul>
					<div v-if="orderDetail.filter(detail => detail.orderid === list.id).length > 2">
						<button v-if="!isExpanded(list.id)" @click="toggleExpand(list.id)" class="expand-button">展开</button>
						<button v-else @click="toggleExpand(list.id)" class="expand-button">收起</button>
					</div>
					<hr class="divider">
				</div>
			</div>

			<!-- 评价表单弹出层 -->
			<div v-if="showReviewForm" class="review-form-overlay">
				<div class="review-form-container">
					<button @click="closeReviewForm" class="close-btn">返回</button>
					<h3>添加评价</h3>
					<form @submit.prevent="submitReview">
						<label>评价的对象:</label>
						<select v-model="newReview.foodid">
							<option v-for="detail in selectedOrderDetails" :key="detail.id" :value="detail.foodid">
								{{ getFoodName(detail.foodid) }}
							</option>
						</select>

						<button @click="addStar()" class="rating" type="button">
							<img :src="starImage" alt="">
							<p>{{ buttonText }}</p>
						</button>

						<label for="reviewText">评价内容：</label>
						<textarea id="reviewText" v-model="newReview.review_text" rows="4" required></textarea>

						<label for="reviewImage">上传图片：</label>
						<input type="file" id="reviewImage" @change="handleFileUpload" accept="image/*">

						<button type="submit">提交评价</button>
					</form>
				</div>
			</div>

		</div>
	</div>
	</div>
</body>
<script>
	new Vue({
		el:'#app',
		data:{
			order:[],//订单中的数据
			orderDetail:[],//订单的详细数据
			foods:[],//食物数据
			userid:0,
			showReviewForm: false,
			newReview: {
				foodid:'',
				star: 5,
				review_text: '',
				review_image_url: null
			},
			dinnerTableId:'',
			expandedOrders: {}
		},
		methods:{
			displayedDetails(orderId) {
				const details = this.orderDetail.filter(detail => detail.orderid === orderId);
				if (this.isExpanded(orderId)) {
					return details;
				}
				return details.slice(0, 2);
			},
			isExpanded(orderId) {
				return this.expandedOrders[orderId] || false;
			},
			toggleExpand(orderId) {
				this.$set(this.expandedOrders, orderId, !this.isExpanded(orderId));
			},
			fetchOrder() {
				this.getUserid()
				let preorders=[];//上一次的数据
				const poll=()=>{
					axios.post("../showOrder", {
						op: "order",
						userid: this.userid
					})
							.then(resp => {
								let neworders=resp.data;
								if (preorders!=null){
									if(neworders.length!==preorders.length){
										console.log("订单发生变化")//如果不是第一次获取的值,发生变化
									}
								}
								this.order = resp.data;
								preorders=this.order;
								setTimeout(poll,3000);//三秒一次
							})
							.catch(error => {
								console.log("获取订单失败", error);
								setTimeout(poll,3000);
								setTimeout(poll,3000);//三秒一次
							});
				}
						poll();
			},
			fetchOrderDetail(){
				const poll=()=>{
					axios.post("../showOrder",{
						op:"orderDetail"
					}).then(rep=>{
						this.orderDetail=rep.data;

						setTimeout(poll,3000);
					}).catch(error=>{
						console.log("获取订单详情失败");
						setTimeout(poll,3000);
					})
				}
			poll();
			},
			fetchFoods(){
				axios.post("../food",{
					op:"fetchFoods"
				}).then(rep=>{
					this.foods=rep.data;
					console.log(this.foods);
				}).catch(error=>{
					console.log("获取食物失败");
				})
			},
			setpayfor(ordercode){
				axios.post("../showOrder",{
					op:"payfor",
					order_code:ordercode
				}).then(resp=>{

				})
			},
			addStar(){
				if (this.newReview.star >1) {
					this.newReview.star -= 1; // 星级增加直到5
				} else {
					this.newReview.star = 5; // 当达到5星后，再次点击重置为0
				}

			},
			getFoodName(foodid) {
				// 根据 foodid 查找对应的食品名字
				const food = this.foods.find(food => food.id === foodid);
				return food ? food.food_name : '未知食品';
			},
			getFoodPrice(foodid) {
				// 根据 foodid 查找对应的价格
				const food = this.foods.find(food => food.id === foodid);
				return food ? food.price : '0.00';
			},
			getFoodDiscount(foodid){
				const food = this.foods.find(food => food.id === foodid);
				return food ? (food.discount*food.price).toFixed(2) : 0;
			},
			getfoodimg(id){
				const food= this.foods.find(food=>food.id===id);
				return food?food.img:'https://daiwei001.oss-cn-beijing.aliyuncs.com/79a997f4c8624d3fa8bd91d2eec50453_香辣牛肉面.jpg';
			},

			 showDate(date) {
				 return `${date[1]}月${date[2]}日 ${date[3]}:${date[4]} `;
				},

		 payfor(list) {
			 // 使用 encodeURIComponent() 编码参数
			 let encodedOrderCode = encodeURIComponent(list.order_code);
			 let encodedTotalPrice = encodeURIComponent(list.total_price);

			 // 使用模板字符串拼接 URL，并打开新窗口
			 this.setpayfor(list.order_code);
			this.release();
			 window.open(`payfor.html?WIDout_trade_no=${encodedOrderCode}&WIDsubject=zf&WIDtotal_amount=${encodedTotalPrice}`, '_blank');

		},
			release(){
				this.getDinnerId();
				const params=new URLSearchParams();
				params.append("tableid",this.dinnerTableId)
				axios.post("../fooddetail?op=release",params).then(resp=>{
					const jm=resp.data;
					if (jm.code===1){
						console.log("释放成功");
					}else {
						console.log("释放失败");
					}
				})
			},
			getDinnerId(){
				this.dinnerTableId=sessionStorage.getItem('dinnerTableId');
			},
			getUserid() {
				const userIdStr = sessionStorage.getItem("userid");
				if (userIdStr !== null) {
				return 	this.userid = parseInt(userIdStr);
				} else {
					// 处理用户未登录时的逻辑，例如跳转到登录页面或者设置默认值
				return 	this.userid = 0; // 设置默认值为0或者其他合适的未登录状态值
				}
			},
			addReview(orderId){

				if (this.getUserid()===0){
					alert("检测到您未登陆暂时无法评价");
					if (confirm("点击确认,立即登陆")){
						window.location.href="login.html";
					}
				}else {
					this.showReviewForm = true; // 显示评价表单
					this.newReview.food_id = ''; // 清空选择的菜品ID
					// 调用方法获取特定订单的菜品详情
					this.selectedOrderDetails = this.getOrderDetails(orderId);

				}
			},
			getOrderDetails(orderId) {
				return this.orderDetail.filter(detail => detail.orderid === orderId);
			},

			closeReviewForm() {
				// 关闭评价表单，重置表单数据
				this.newReview = {
					foodid:'',
					star: '',
					review_text: '',
					review_image_url: null
				};
				this.showReviewForm = false;
			},
			handleFileUpload(event) {
				// 处理文件上传，获取文件对象并存储到 newReview 中
				this.newReview.review_image_url = event.target.files[0];
			},
			submitReview() {
				// 在这里可以提交评价的逻辑，可以将 this.newReview 发送到后端保存
				console.log('提交评价', this.newReview);
				this.submitReviewtoser(this.newReview)
				this.closeReviewForm();
			},
			submitReviewtoser(newReview){
				this.getUserid();
				var formData = new FormData();
				formData.append('userid',this.userid);
				formData.append('foodid',newReview.foodid);
				formData.append('star', newReview.star);
				formData.append('review_text', newReview.review_text);
				formData.append('review_image', newReview.review_image_url);
				console.log(formData);
				console.log(newReview);
				axios.post("../fooddetail?op=addReviews", formData, {
					headers: {
						'Content-Type': 'multipart/form-data'
					}
				}).then(result => {
					var jsonmodel = result.data;
					if (jsonmodel.code === 1) {
						alert("添加成功")
					} else {
						alert("添加失败");
					}
				})
			}

		},
		computed: {
			// 计算属性来决定显示哪张星级图片
			starImage() {
				return `../images/${this.newReview.star}星.png`;
			},
			// 根据星级显示不同的提示词
			buttonText() {
				if (this.newReview.star === 1) {
					return "超级无敌不满意";
				} else if (this.newReview.star === 2){
					return "一般般不推荐";
				} else if (this.newReview.star === 3){
					return "也就还行吧";
				}else if (this.newReview.star === 4){
					return "很满意";
				}else if (this.newReview.star === 5){
					return "超级无敌满意";
				}else {
					return ''
				}
			}
		},
		mounted(){
			this.fetchOrder();
			this.fetchOrderDetail();
			this.fetchFoods();

		}
	})
</script>
</html>